<?php
/**
 * WechatController.class.php
 * 微信控制器
 *
 * @author  王中艺
 * @date    2016-09-20
 */

namespace Wechat\Controller;
use Think\Controller;

class WechatController extends Controller {
    public $wechat;
    public $openId;
    public $userInfo;

    function _initialize(){
        $this->wechat   = \Wechat\Util\WechatExt::getInstance();
    }

    function test(){
        echo $this->wechat->getOauthRedirect(C('SERVER_NAME').'/wechat/html/index.html?#/User/index');
        // //院长二维码生成
        // $scene  = json_encode(array('cate' => 'dean'));
        // $qrCode     = $this->wechat->getQRCode($scene,2);
        // dump($this->wechat->getQRUrl($qrCode['ticket']));
    }

    function index(){
        //验证
        $this->wechat->valid();
        //获取消息
        $this->wechat->getRev();
        //获取OpenId
        $this->openId   = $this->wechat->getRevFrom();
        
        $revType  = $this->wechat->getRevType();
        switch($revType){
            //事件处理
            case 'event':
                $this->dealEventMsg();  
            break;

            //其他处理
            default:
                //同步用户信息
                $this->synchUserInfo();
                echo '';
                // $this->reply();
            break;
        }
    }

    /**
     * 处理事件消息
     * @return null 
     */
    private function dealEventMsg(){
        $eventType  = $this->wechat->getRevEvent();
        switch($eventType['event']){
            //关注事件
            case 'subscribe':   $this->subscribe(); break;

            //取消关注事件
            case 'unsubscribe':
                D('User')->unsubscribe($this->openId);
                $this->reply();
            break;

            //忽略打开连接事件
            case 'VIEW':
                echo '';
            break;

            default:
                //同步用户信息
                $this->synchUserInfo();
                echo '';
                // $this->reply();
            break;
        }
    }

    /**
     * 同步用户信息   
     * @return [type] [description]
     */
    private function synchUserInfo(){
        $userInfo   = D('User')->getUserInfo($this->openId);
        if($userInfo){
        	//检测角色信息有效性
            if(!$userInfo['role_id']){
                $this->wechat->updateGroupMembers(106, $this->openId);
                $userInfo['role_id']    = 106;
            }else{
                $wxUserInfo    = $this->wechat->getUserInfo($this->openId);
                if(!$wxUserInfo) 
                    return true;

                if($userInfo['role_id'] != D('User')::ROLE_MAP[$wxUserInfo['groupid']]){
                    $this->wechat->updateGroupMembers(106, $this->openId);
                    $userInfo['role_id']    = 106;
                }
            } 

            D('User')->updateUserInfo($userInfo['id'], $userInfo);
		}else{
            //注册用户角色
            $this->wechat->updateGroupMembers(106, $this->openId);
            //信息入库
            $userInfo   = $this->wechat->getUserInfo($this->openId);
            $userId     = D('User')->addUser($userInfo);
            //注册游离用户关系
            $relaInfo   = array(
                'user_id' => $userId,
                'dean_id'   => -1,
                'expand_id' => -1,
                'teacher_id'    => -1,
                'parent_id' => 0
            );
            D('User')->addUserRelaInfo($userId, $relaInfo);
        }
    }

    /**
     * 回推默认消息
     * @return null 
     */
    private function reply(){
        $content    = $this->wechat->getRevContent();
        $reply  = sprintf("欢迎订阅小沫沫推推~\n".
            "每个家庭，都该是欣欣向荣的一片乐土。\n".
            "我们坚持中医小儿健康教育内容，陪伴你和孩子一同幸福成长。\n\n".
            unicode2utf8("\ue231")."【<a href='%s'>做父母必备的常识</a>】".unicode2utf8("\ue230")."\n",
            $this->wechat->getOauthRedirect(C('SERVER_NAME').'/wechat/html/index.html?#/Course/free')
        );
        $this->wechat->text($reply)->reply();
    }

    /**
     * 处理关注事件
     */
    private function subscribe(){
        //查看用户是否存在
        $userInfo   = D('User')->getUserInfo($this->openId);
        if($userInfo){
            //用户存在
            $userId     = $userInfo['id'];
            $groupId    = $userInfo['role_id'];
            if(!$groupId)   $groupId    = 106;
            $this->wechat->updateGroupMembers($groupId, $this->openId);
            $userInfo   = $this->wechat->getUserInfo($this->openId);
            D('User')->updateUserInfo($userId, $userInfo);
        }else{
            //用户不存在
            $scene    = $this->wechat->getRevSceneId();
            $relaInfo   = $this->getUserRole($scene);
			//设置用户分组
            $this->wechat->updateGroupMembers($relaInfo['group_id'], $this->openId);
            //用户信息获取
            $userInfo   = $this->wechat->getUserInfo($this->openId);
            if($userInfo){
                $userInfo['recom_id']   = $relaInfo['recom_id'];
                //添加用户
                $userId     = D('User')->addUser($userInfo);
                //用户关系链写入
                D('User')->addUserRelaInfo($userId, $relaInfo);
            }
            
        }

        $this->reply();
    }

    /**
     * 设置用户分组
     * @param   $scene    场景值
     * @return  $roleInfo   用户关系表
     */
    private function getUserRole($scene){
        $groupId    = 106;
        //普通推荐渠道
        if(is_numeric($scene)){
            //普通二维码扫描
            $recomId    = $scene;
            $recomRelaInfo  = D('User')->getUserRelaInfo($recomId);
            if(!$recomRelaInfo){
                //无效推荐人关系
                $relaInfo  = array(
                    'dean_id' => -1, 
                    'expand_id' => -1, 
                    'teacher_id' => -1, 
                    'parent_id' => 0,
                    'recom_id'  => -1
                );
            }else{
                $relaInfo   = $recomRelaInfo;
                foreach($recomRelaInfo as $key=>$val){
                    //更改上层身份
                    if($val == 0 || $key == 'parent_id'){
                        $relaInfo[$key] = $recomId;
                        break;
                    }
                }
                //检测上层身份是否为家长
                if($relaInfo['parent_id'] == -1){
                    $relaInfo['parent_id'] = 0;
                }

                $relaInfo['recom_id']   = $recomId;
            }
        }else{
            $scene  = json_decode($scene, true);
            switch($scene['cate']){
                //院长注册
                case 'dean':
                    $groupId    = 101;
                    $relaInfo   = array(
                        'dean_id'   => 0,
                        'expand_id' => -1,
                        'teacher_id'=> -1,
                        'parent_id' => -1,
                        'recom_id'  => 0
                    );
                break;

                //推销员注册
                case 'sale':
                    //默认推销员a
                    $groupId    = 102;
                    $realInfo   = array(
                        'dean_id'   => $scene['recom_id'],
                        'expand_id' => 0,
                        'teacher_id'    => -1,
                        'parent_id' => -1,
                        'recom_id'  => $scene['recom_id']
                    );
                break;

                //直接关注
                default:
                    $relaInfo   = array(
                        'dean_id'   => -1,
                        'expand_id' => -1,
                        'teacher_id'=> -1,
                        'parent_id' => 0,
                        'recom_id'  => -1
                    );
                    $groupId    = 106;
                break;
            }
        }
        $relaInfo['group_id']   = $groupId;
        return $relaInfo;
    }

    

    /**
     * 初始化微信设置
     * 设置分组
     * 创建菜单
     */
    public function initWechat(){

        //菜单设置
        $this->wechat->deleteMenu();
        //通用菜单设置
        $commonMenu['button']     = [
            ['name' => '健康课堂', 'sub_button' => [
                [
                    'type' => 'view', 
                    'name' => '免费课程', 
                    'url' => $this->wechat->getOauthRedirect(C('SERVER_NAME').'/wechat/html/index.html?#/Course/free')
                ],[
                    'type' => 'view', 
                    'name' => '父母必修课', 
                    'url' => $this->wechat->getOauthRedirect(C('SERVER_NAME').'/wechat/html/index.html?cate=1&#/Course/index')
                ]
            ]],
            ['name' => '沫言电台', 'sub_button' => [
                [
                    'type' => 'view', 
                    'name' => '收听沫言电台', 
                    'url' => $this->wechat->getOauthRedirect(C('SERVER_NAME').'/wechat/html/index.html?#/RadioMorning/index')
                ],[
                    'type' => 'view', 
                    'name' => '会员专享', 
                    'url' => $this->wechat->getOauthRedirect(C('SERVER_NAME').'/wechat/html/index.html#/BBS/index')
                ]
            ]],
            ['name' => '用户中心', 'sub_button' => [
                [
                    'type' => 'view', 
                    'name' => '个人中心', 
                    'url' => $this->wechat->getOauthRedirect(C('SERVER_NAME').'/wechat/html/index.html?#/User/index')
                ],[
                    'type' => 'view', 
                    'name' => '招生加盟', 
                    'url' => 'http://mp.weixin.qq.com/s/cS5AErEAMC-i9UsaRLcTpQ'
                ]
            ]],
        ];

        echo 'Common Menu set is '.$this->wechat->createMenu($commonMenu).'<br>';
        
		//销售菜单设置
        $soleMenu['button'] = $commonMenu['button'];
        $soleMenu['button'][2]['sub_button'][]  = ['type' => 'view', 'name' => '销售中心', 'url' => $this->wechat->getOauthRedirect(C('SERVER_NAME').'/wechat/html/index.html?#/Sole/index')];

        $soleMenu['matchrule']['group_id']   = 117;
        echo 'Sole Menu 117 set is:'.$this->wechat->addconditionalMenu($soleMenu).'<br>';
        $soleMenu['matchrule']['group_id']   = 113;
        echo 'Sole Menu 113 set is:'.$this->wechat->addconditionalMenu($soleMenu).'<br>';
        $soleMenu['matchrule']['group_id']   = 114;
        echo 'Sole Menu 114 set is:'.$this->wechat->addconditionalMenu($soleMenu).'<br>';
        $soleMenu['matchrule']['group_id']   = 115;
        echo 'Sole Menu 115 set is:'.$this->wechat->addconditionalMenu($soleMenu).'<br>';
        $soleMenu['matchrule']['group_id']   = 116;
        echo 'Sole Menu 116 set is:'.$this->wechat->addconditionalMenu($soleMenu).'<br>';

        echo 'Menu set error code:'.$this->wechat->errCode.'<br>';

        //菜单列表
        $menu   = $this->wechat->getMenu();
        echo 'Now menu is:<br>';
        dump($menu);
    }
}
